<template>
  <el-row>
    <el-col :span="24">
      <!-- <basic-container> -->
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        ref="crud"
        v-model="form"
        :permission="permissionList"
        @row-del="rowDel"
        @row-update="rowUpdate"
        @row-save="rowSave"
        :before-open="beforeOpen"
        :page.sync="page"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            plain
            icon="el-icon-delete"
            @click="handleDelete"
            >删 除
          </el-button>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button
            type="text"
            size="small"
            icon="el-icon-setting"
            @click="handleRole(scope.row)"
            >权限设置
          </el-button>
        </template>
      </avue-crud>
      <el-dialog
        title="角色权限配置"
        append-to-body
        :visible.sync="box"
        top="72px"
        width="345px"
      >
        <el-tabs type="border-card">
          <el-tab-pane label="菜单权限">
            <el-tree
              :data="menuGrantList"
              show-checkbox
              check-strictly
              node-key="id"
              ref="treeMenu"
              :default-checked-keys="menuTreeObj"
              :default-expanded-keys="expandedKeys"
              class="menuGrantList"
              :props="props"
            >
            </el-tree>
          </el-tab-pane>
        </el-tabs>
        <span slot="footer" class="dialog-footer">
          <el-button @click="box = false">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </span>
      </el-dialog>
      <!-- </basic-container> -->
    </el-col>
  </el-row>
</template>

<script>
import {
  getList,
  remove,
  update,
  add,
  getRole,
  grant,
} from "@/api/system/role";
import { getLazyList } from "@/api/system/menu";
import { byteLength } from "@/utils/index";

export default {
  data() {
    const validatName = (rule, value, callback) => {
      if (byteLength(value) < 2 || byteLength(value) > 20) {
        callback(new Error("请输入2-20位英文字符或1-10位中文字符"));
      } else {
        callback();
      }
    };
    const validAlphabetsASNum = (rule, value, callback) => {
      if (!/^[a-zA-Z0-9_]+$/.test(value)) {
        callback(new Error("只能输入英文、数字或下划线"));
      } else {
        callback();
      }
    };
    return {
      form: {},
      box: false,
      props: {
        label: "menuName",
        value: "id",
      },
      menuGrantList: [],
      menuTreeObj: [],
      selectionList: [],
      expandedKeys: [],
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        rowKey: "roleId",
        columnBtn: false,
        searchShowBtn: false,
        refreshBtn: false,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        tree: true,
        border: true,
        index: true,
        selection: true,
        viewBtn: true,
        dialogWidth: 500,
        dialogClickModal: false,
        menuWidth: 300,
        column: [
          {
            label: "角色名称",
            prop: "roleName",
            search: true,
            span: 24,
            labelWidth: 100,
            rules: [
              {
                required: true,
                message: "请输入角色名称",
                trigger: "blur",
              },
              { validator: validatName, trigger: "blur" },
            ],
          },
          {
            label: "权限字符串",
            prop: "roleKey",
            search: true,
            span: 24,
            searchLabelWidth: 100,
            labelWidth: 100,
            rules: [
              {
                required: true,
                message: "请输入权限字符串",
                trigger: "blur",
              },
              { validator: validAlphabetsASNum, trigger: "blur" },
              {
                min: 2,
                max: 32,
                message: "请输入2-32位字符",
                trigger: "blur",
              },
            ],
          },
          {
            label: "角色排序",
            prop: "roleSort",
            type: "number",
            span: 24,
            labelWidth: 100,
            min: 0,
            max: 9999,
            rules: [
              {
                required: true,
                message: "请输入角色排序",
                trigger: "blur",
              },
            ],
          },
        ],
      },
      data: [],
      selectRoleId: "",
    };
  },
  watch: {},
  computed: {
    permissionList() {
      return {
        addBtn: true,
        viewBtn: true,
        delBtn: true,
        editBtn: true,
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.roleId);
      });
      return ids;
    },
  },
  mounted() {
    // this.initData();
  },
  methods: {
    submit() {
      const menuList = this.$refs.treeMenu.getCheckedKeys();
      grant(this.selectRoleId, menuList).then(() => {
        this.box = false;
        this.$message({
          type: "success",
          message: "操作成功!",
        });
        this.onLoad(this.page);
      });
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          //console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          //console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove([row.roleId]);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    beforeOpen(done, type) {
      this.initFlag = true;
      done();
    },
    handleRole(row) {
      this.selectRoleId = row.roleId;
      this.menuTreeObj = [];
      getLazyList().then((res) => {
        this.menuGrantList = res.data;
        this.box = true;
        if (this.expandedKeys.length == 0) {
          this.expandedKeys = res.data.map((item, index) => {
            return item.id;
          });
        }
      });
      getRole(row.roleId).then((res) => {
        this.menuTreeObj = res.data;
      });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList({
        current: page.currentPage,
        size: page.pageSize,
        ...Object.assign(params, this.query),
      }).then((res) => {
        const data = res.data;
        this.data = data.records;
        this.page.total = data.total;
        this.loading = false;
        this.selectionClear();
      });
    },
  },
};
</script>

<style>
.menuGrantList {
  max-height: 380px;
  overflow: auto;
}
</style>
